/*
 * Digital Audio Mobile - A multi track studio for Windows Mobile
 * Copyright (C) 2008 David Olsson
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include <aygshell.h>
#include <commctrl.h>

#include "AboutDialog.h"
#include "AudioBuffer.h"
#include "Composition.h"
#include "CompositionInfoControl.h"
#include "DamDialog.h"
#include "Resources.h"
#include "Segment.h"
#include "Track.h"
#include "TrackInfoControl.h"
#include "TrackRollControl.h"
#include "WaveFile.h"

DamDialog::DamDialog(HINSTANCE hInstance, InputDevice *inDevice, OutputDevice *outDevice) throw(): Dialog(hInstance, TEXT("Digital Audio Mobile"), CS_CLOSE), m_inDevice(inDevice), m_inBuffer1(0), m_inBuffer2(0), m_outDevice(outDevice), m_outBuffer1(0), m_outBuffer2(0), m_compositionInfo(0), m_trackInfo(0), m_trackRoll(0), m_composition(0), m_waveFile(0) {
    m_inDevice->addBufferHandler(this);
    m_inBuffer1 = m_inDevice->createCompatibleBuffer(BUFFERSIZE);
    m_inBuffer2 = m_inDevice->createCompatibleBuffer(BUFFERSIZE);
    
    m_outDevice->addBufferHandler(this);
    m_outBuffer1 = m_outDevice->createCompatibleBuffer(BUFFERSIZE);
    m_outBuffer2 = m_outDevice->createCompatibleBuffer(BUFFERSIZE);

    m_composition = new Composition();

    m_compositionInfo = new CompositionInfoControl(this, m_composition);
    m_trackInfo = new TrackInfoControl(this, height() - m_compositionInfo->height());
    m_trackRoll = new TrackRollControl(this, height() - m_compositionInfo->height() - m_trackInfo->height(), m_composition);

    TBBUTTONINFO bi;
    ZeroMemory(&bi, sizeof(TBBUTTONINFO));
    bi.cbSize = sizeof(TBBUTTONINFO);
    bi.dwMask = TBIF_TEXT | TBIF_STATE;
    bi.pszText = TEXT("Play");
    bi.fsState = TBSTATE_ENABLED;
    SendMessage(hMenuBar(), TB_SETBUTTONINFO, ID_BUTTON, LPARAM(&bi));

    HMENU hMenu = enableMenu(TEXT("Menu"));
    AppendMenu(hMenu, MF_ENABLED | MF_STRING, ID_SETTINGS, TEXT("Settings..."));
    AppendMenu(hMenu, MF_ENABLED | MF_STRING, ID_ABOUT, TEXT("About..."));
    AppendMenu(hMenu, MF_SEPARATOR, 0, 0);
    AppendMenu(hMenu, MF_GRAYED | MF_STRING, ID_RECORD, TEXT("Start recording"));
}

DamDialog::~DamDialog() {
    if(m_composition != 0) {
        delete(m_composition);
    }
    if(m_trackRoll != 0) {
        delete(m_trackRoll);
    }
    if(m_trackInfo != 0) {
        delete(m_trackInfo);
    }
    if(m_compositionInfo != 0) {
        delete(m_compositionInfo);
    }

    if(m_outBuffer2 != 0) {
        delete(m_outBuffer2);
    }
    if(m_outBuffer1 != 0) {
        delete(m_outBuffer1);
    }
    if(m_outDevice != 0) {
        delete(m_outDevice);
    }
    if(m_inBuffer2 != 0) {
        delete(m_inBuffer2);
    }
    if(m_inBuffer1 != 0) {
        delete(m_inBuffer1);
    }
    if(m_inDevice != 0) {
        delete(m_inDevice);
    }
}

void DamDialog::setCurrentTrack(Track *track) throw() {
    m_trackInfo->setCurrentTrack(track);

    EnableMenuItem(hMenu(), ID_RECORD, (track == 0 || m_outDevice->isPlaying()) ? MF_GRAYED : MF_ENABLED);
}

void DamDialog::updateSongPosition(const MusicTime &pos) throw() {
    m_compositionInfo->updateSongPosition(pos);
}

void DamDialog::togglePlay() throw() {
    if(m_outDevice->isPlaying()) {
        m_outDevice->stop();
        m_trackRoll->resetSongPosition();
        m_compositionInfo->updateSongPosition(m_trackRoll->currentSongPosition());
    }
    else {
        m_clickGen.reset(m_trackRoll->currentSongPosition(), m_composition->beatsPerMinute(), m_composition->beatsPerMeasure(), m_composition->beatNoteType());
        m_clickGen.generateClicks(m_outBuffer1);
        m_outDevice->enqueueBuffer(m_outBuffer1);
        m_clickGen.generateClicks(m_outBuffer2);
        m_outDevice->enqueueBuffer(m_outBuffer2);
        m_outDevice->play();
    }
}

void DamDialog::toggleRecord() throw() {
    if(m_inDevice->isRecording()) {
        m_inDevice->stop();
        m_trackRoll->resetSongPosition();
        m_compositionInfo->updateSongPosition(m_trackRoll->currentSongPosition());

        // Finalize the wave file.
        m_waveFile->finalize();
        delete(m_waveFile);

        // Create the audiosegment.
        Segment *seg = new Segment(m_recStart);
        seg->setSource(m_waveFilename);
        m_trackRoll->currentTrack()->addSegment(seg);
    }
    else {
        // Create the filename for the wave file we're about to record.
        TCHAR path[MAX_PATH];
        SHGetSpecialFolderPath(0, path, CSIDL_PERSONAL, TRUE);
        _tcscat(path, TEXT("\\Digital Audio Mobile"));
        CreateDirectory(path, 0);
        GetTempFileName(path, TEXT("dam"), 0, m_waveFilename);
        DeleteFile(m_waveFilename);
        _tcscpy(m_waveFilename + _tcslen(m_waveFilename) - 4, TEXT(".wav"));
        // Write WAVE file header.
        m_waveFile = WaveFile::create(m_waveFilename, m_inBuffer1->samplesPerSecond(), m_inBuffer1->numChannels(), m_inBuffer1->bytesPerSample());

        // Start the recording (and playback).
        m_recStart = m_trackRoll->currentSongPosition();
        m_inDevice->enqueueBuffer(m_inBuffer1);
        m_inDevice->enqueueBuffer(m_inBuffer2);
        m_inDevice->record();
        togglePlay();
    }
}

bool DamDialog::close(CloseCommand cc) throw() {
    m_outDevice->stop();
    return(true);
}

void DamDialog::controlNotification(HWND hWnd, WPARAM notification) throw() {
}

void DamDialog::menuNotification(unsigned int itemId) throw() {
    if(itemId == ID_BUTTON) {
        if(m_inDevice->isRecording()) {
            toggleRecord();
        }
        togglePlay();
        TBBUTTONINFO bi;
        ZeroMemory(&bi, sizeof(TBBUTTONINFO));
        bi.cbSize = sizeof(TBBUTTONINFO);
        bi.dwMask = TBIF_TEXT | TBIF_STATE;
        bi.fsState = TBSTATE_ENABLED;
        if(m_outDevice->isPlaying()) {
            bi.pszText = TEXT("Stop");
            SendMessage(hMenuBar(), TB_SETBUTTONINFO, ID_BUTTON, LPARAM(&bi));
            EnableMenuItem(hMenu(), ID_RECORD, MF_GRAYED);
        }
        else {
            bi.pszText = TEXT("Play");
            SendMessage(hMenuBar(), TB_SETBUTTONINFO, ID_BUTTON, LPARAM(&bi));
            EnableMenuItem(hMenu(), ID_RECORD, (m_trackRoll->currentTrack() == 0) ? MF_GRAYED : MF_ENABLED);
        }
    }
    else if(itemId == ID_SETTINGS) {
    }
    else if(itemId == ID_ABOUT) {
        AboutDialog aboutDlg(GetModuleHandle(0));
        aboutDlg.open();
    }
    else if(itemId == ID_RECORD) {
        toggleRecord();
        TBBUTTONINFO bi;
        ZeroMemory(&bi, sizeof(TBBUTTONINFO));
        bi.cbSize = sizeof(TBBUTTONINFO);
        bi.dwMask = TBIF_TEXT | TBIF_STATE;
        bi.fsState = TBSTATE_ENABLED;
        bi.pszText = TEXT("Stop");
        SendMessage(hMenuBar(), TB_SETBUTTONINFO, ID_BUTTON, LPARAM(&bi));
        EnableMenuItem(hMenu(), ID_RECORD, MF_GRAYED);
    }
}

void DamDialog::started(Device *device) throw() {
}

void DamDialog::stopped(Device *device) throw() {
}

void DamDialog::bufferCompleted(Device *device, const AudioBuffer *buffer) throw() {
    if(device == m_outDevice) {
        if(buffer == m_outBuffer1) {
            m_clickGen.generateClicks(m_outBuffer1);
            m_outDevice->enqueueBuffer(m_outBuffer1);
        }
        else if(buffer == m_outBuffer2) {
            m_clickGen.generateClicks(m_outBuffer2);
            m_outDevice->enqueueBuffer(m_outBuffer2);
        }
        m_trackRoll->updateSongPosition(MusicTime(BUFFERSIZE, buffer->samplesPerSecond()));
    }
    else {
        if(buffer == m_inBuffer1) {
            m_waveFile->write(m_inBuffer1);
            m_inDevice->enqueueBuffer(m_inBuffer1);
        }
        else if(buffer == m_inBuffer2) {
            m_waveFile->write(m_inBuffer2);
            m_inDevice->enqueueBuffer(m_inBuffer2);
        }
    }
}

const unsigned int DamDialog::BUFFERSIZE = 8192;
const unsigned int DamDialog::ID_SETTINGS = 1;
const unsigned int DamDialog::ID_ABOUT = 2;
const unsigned int DamDialog::ID_RECORD = 3;
